/*
 * Serum
 *
 * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
 */

Serum.Form.Module.Fields.OneToMany = Ext.extend(Ext.Panel, {

    /**
     * Constructor
     *
     * @param   {Object}    baseConfig
     */
    constructor: function(baseConfig) {

        this.listPanel = new Serum.Form.Module.Fields.OneToManyPreview(baseConfig);

        Serum.Form.Module.Fields.OneToMany.superclass.constructor.call(this, Ext.apply({
            border: false,

            items: [
                this.listPanel
            ]
        }, baseConfig));
    }
});

Serum.Form.Module.Fields.OneToManyPreview = Ext.extend(Ext.grid.GridPanel, {

    /**
     * Constructor
     *
     * @param   {Object}    config
     */
    constructor: function(config) {
        this.module         = config.module         || Serum.Selector.get().module
        this.controller     = config.controller     || 'Index';
        this.action         = config.action         || 'edit';
        this.parentRoot     = config.id             || Serum.Selector.get().getParams['id'];
        this.fieldsList     = config.fieldsList     || undefined;

        var _fields         = ['id', 'title', 'status'];
        if (typeof config.extraFields !== 'undefined') {
            for(var i = 0; i < config.extraFields.length; i++) {
                _fields.push(config.extraFields[i]);
            }
        }

        var _sort               = config.sort           || { sort: 'id', dir: 'DESC' };
        var _pageSize           = config.pageSize       || Serum.Preferences.get().getValue('ELEMENTS_PER_PAGE');
        var _selectionModel     = config.selectionModel || new Ext.grid.CheckboxSelectionModel();
        var _method             = Serum.Selector.get().method({ controller: this.controller, action: 'index' });
        var _editable           = (typeof config.editable === 'undefined') ? true : config.editable;

        // Data store
        this.store = new Ext.data.JsonStore({
            root:           'result',
            totalProperty:  'count',
            id:             'id',

            fields:         _fields,

            url:            Serum.Selector.get().requestUrl(),
            remoteSort:     true,
            baseParams:     {
                                method:     _method,
                                requestId:  Serum.Helper.Request.id(),
                                parentRoot: this.parentRoot
                            }
        });

        this.store.setDefaultSort(_sort.sort, _sort.dir);
        this.store.reload({
                params: { start: 0, limit: _pageSize }
            });

        // Columns configuration
        this.columns    = config.columns ||
                          [{
                                id:         'title',
                                header:     __('base~list_column_title'),
                                dataIndex:  'title',
                                sortable:   false
                            }];
        var _autoExpandColumn  = config.autoExpandColumn || this.columns[0].id;
        this.columns.unshift(_selectionModel);

        // Rows style
        this.getView().getRowClass = function(record, index) {
            return (record.data.status == 1) ? 'disabled-element' : 'enabled-element';
        };

        // Toolbar configuration
        this.toolbar = new Array();
        if (typeof config.toolbar !== 'undefined') {
            var item = null;
            for(var i = 0; i < config.toolbar.length; i++) {
                item = config.toolbar[i];

                if (item == '-') {
                    this.toolbar.push('-');

                } else {
                    item.parentRoot = this.parentRoot;
                    item.controller = this.controller;
                    item.action     = this.action;
                    item.viewer     = this;

                    if (typeof item.config !== 'undefined') {
                        this.toolbar.push({
                            tooltip:    item.config.tooltip,
                            iconCls:    item.config.iconCls,
                            handler:    item.config.handler,
                            scope:      item.config.scope
                        });

                    } else {
                        this.toolbar.push({
                            tooltip:    item.tooltip,
                            iconCls:    item.iconCls,
                            handler:    item.handler,
                            scope:      item.scope
                        });
                    }
                }
            }
        }

        // Paginator
        this.pagingBar  = new Ext.PagingToolbar({
                            pageSize:       _pageSize,
                            store:          this.store,
                            displayInfo:    true,
                            displayMsg:     __('base~list_displayMsg'),
                            emptyMsg:       __('base~list_emptyMsg')
                        });

        // Parent constructor
        Serum.Form.Module.Fields.OneToManyPreview.superclass.constructor.call(this, {
            id:                 'element-grid-' + _method,
            loadMask:           {msg: __('base~list_loading')},
            autoExpandColumn:   _autoExpandColumn,
            border:             false,
            tbar:               this.toolbar,
            sm:                 _selectionModel,
            width:              420,
            height:             200,

            viewConfig: {
                forceFit:       false,
                enableRowBody:  true,
                showPreview:    false
            },

            bbar: this.pagingBar
        });

        // Events
        if (_editable === true) {
            var onEditElement = config.onEditElement || this.onEditElement;
            this.on('rowdblclick', onEditElement, this);
        }

        Serum.App.get().eventListener.on('onetomany' + config.controller + 'edited', function() { this.store.reload({params: {start: 0, limit: _pageSize}}); }, this);
    },

    /**
     * Event handler
     */
    onEditElement: function() {
        var self = this;

        var onSuccess = function() {
            win.close();
            Serum.App.get().eventListener.fireEvent('onetomany' + self.controller + 'edited');
        }

        var form    = Serum.Form.Module.Edit({}, { controller: this.controller, action: this.action, parentRoot: this.parentRoot }, onSuccess);

        var win = new Ext.Window({
            layout:     'fit',
            width:      500,
            height:     400,
            closable:   true,
            resizable:  false,
            plain:      true,
            border:     false,
            autoScroll: true,
            modal:      true,
            items:      [
                            form
                        ]
        });
        var splittedId  = this.getSelectionModel().getSelected().data.id.split('-');
 		var id          = splittedId[1];
        form.preload(id);
        form.load(this.fieldsList);

        win.show();
    }
});

Serum.Form.Module.Fields.OneToManyToolbarButton = function(baseConfig) {
    return Ext.apply({
        parentRoot: null,
        viewer:     null

    }, baseConfig);
};

Serum.Form.Module.Fields.OneToManyAdd = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyAdd.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_add_title'), text: __('base~list_action_add_description')},
            iconCls:    'img-add',
            handler:    this.onNewElement,
            scope:      this,
            fieldsList: null

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onNewElement: function() {
        var self = this;

        var onSuccess = function() {
            win.close();
            Serum.App.get().eventListener.fireEvent('onetomany' + self.config.controller + 'edited');
        }

        var form = new Serum.Form.Module.Edit({}, { controller: this.config.controller, action: this.config.action, parentRoot: this.config.parentRoot }, onSuccess);

        var win = new Ext.Window({
            layout:     'fit',
            width:      500,
            height:     400,
            closable:   true,
            resizable:  false,
            plain:      true,
            border:     false,
            autoScroll: true,
            modal:      true,
            items:      [
                            form
                        ]
        });

        form.preload(null);
        form.load(this.config.fieldsList);

        win.show();
    }
});

Serum.Form.Module.Fields.OneToManyEnable = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyEnable.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_enable_title'), text: __('base~list_action_enable_description')},
            iconCls:    'img-enable',
            handler:    this.onEnableElement,
            scope:      this

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onEnableElement: function() {
        var objectsList     = this.config.viewer.getSelectionModel().getSelections();
        var listeId         = new Array();

        for (id = 0 ; id < objectsList.length ; id++) {
            var ids = objectsList[id].data.id.split('-');
            listeId.push(ids[1]);
        }

        Serum.Ajax.request({
            scope:       this,
            params:      {
                            method:     Serum.Selector.get().method({ controller: this.config.controller, action: 'enable' }),
                            requestId:  Serum.Helper.Request.id(),
                            listeId:    listeId.implode('-')
                        },
            onSuccess:  function() { Serum.App.get().eventListener.fireEvent('onetomany' + this.config.controller + 'edited'); }
        });
    }
});

Serum.Form.Module.Fields.OneToManyImport = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyEnable.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_import_title'), text: __('base~list_action_import_description')},
            iconCls:    'img-import',
            handler:    this.onImportElement,
            scope:      this

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onImportElement: function() {
        Serum.Ajax.request({
            scope:       this,
            params:      {
                            method:     Serum.Selector.get().method({ controller: this.config.controller, action: 'importProducts' }),
                            requestId:  Serum.Helper.Request.id(),
                            id:         Serum.Selector.get().getParams['id']
                        },
            onSuccess:  function() { Serum.App.get().eventListener.fireEvent('onetomany' + this.config.controller + 'edited'); }
        });
    }
});

Serum.Form.Module.Fields.OneToManyDisable = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyDisable.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_disable_title'), text: __('base~list_action_disable_description')},
            iconCls:    'img-disable',
            handler:    this.onDisableElement,
            scope:      this

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onDisableElement: function() {
        var objectsList     = this.config.viewer.getSelectionModel().getSelections();
        var listeId         = new Array();

        for (id = 0 ; id < objectsList.length ; id++) {
            var ids = objectsList[id].data.id.split('-');
            listeId.push(ids[1]);
        }

        Serum.Ajax.request({
            scope:       this,
            params:     {
                            method:     Serum.Selector.get().method({ controller: this.config.controller, action: 'disable' }),
                            requestId:  Serum.Helper.Request.id(),
                            listeId:    listeId.implode('-')
                        },
            onSuccess:  function() { Serum.App.get().eventListener.fireEvent('onetomany' + this.config.controller + 'edited'); }
        });
    }
});

Serum.Form.Module.Fields.OneToManyDelete = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyDelete.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_delete_title'), text: __('base~list_action_delete_description')},
            iconCls:    'img-delete',
            handler:    this.onDeleteElement,
            scope:      this

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onDeleteElement: function() {
        var objectsList     = this.config.viewer.getSelectionModel().getSelections();
        var listeId         = new Array();

        for (id = 0 ; id < objectsList.length ; id++) {
            var ids = objectsList[id].data.id.split('-');
            listeId.push(ids[1]);
        }

        Serum.Ajax.request({
            scope:      this,
            params:     {
                            method:     Serum.Selector.get().method({ controller: this.config.controller, action: 'moveTrash' }),
                            requestId:  Serum.Helper.Request.id(),
                            listeId:    listeId.implode('-')
                        },
            onSuccess:  function() { Serum.App.get().eventListener.fireEvent('onetomany' + this.config.controller + 'edited'); }
        });
    }
});

Serum.Form.Module.Fields.OneToManyMultipleEdit = Ext.extend(Serum.Form.Module.Fields.OneToManyToolbarButton, {

    /**
     * Constructor
     *
     * @param   {Object}    _baseConfig
     */
    constructor: function(_baseConfig) {
        var baseConfig = Serum.Form.Module.Fields.OneToManyMultipleEdit.superclass.constructor.call(this, _baseConfig);

        this.config = Ext.apply({
            tooltip:    {title: __('base~list_action_multipleedit_title'), text: __('base~list_action_multipleedit_description')},
            iconCls:    'img-multipleedit',
            handler:    this.onMultipleEditElement,
            scope:      this,
            fieldsList: null

        }, baseConfig);

        return this.config;
    },

    /**
     * Event handler
     */
    onMultipleEditElement: function() {
        var self            = this;
        var objectsList     = this.config.viewer.getSelectionModel().getSelections();
        var listeId         = new Array();

        for (id = 0 ; id < objectsList.length ; id++) {
            listeId.push(objectsList[id].data.id);
        }

        var onSuccess = function() {
            win.close();
            Serum.App.get().eventListener.fireEvent('onetomany' + self.config.controller + 'edited');
        }

        var form = new Serum.Form.Module.Edit({}, { controller: this.config.controller, parentRoot: this.config.parentRoot }, onSuccess);

        var win = new Ext.Window({
            layout:     'fit',
            width:      500,
            height:     400,
            closable:   true,
            resizable:  false,
            plain:      true,
            border:     false,
            autoScroll: true,
            modal:      true,
            items:      [
                            form
                        ]
        });

        form.preload(listeId);
        form.load(this.config.fieldsList);

        win.show();
    }
});

Ext.reg('onetomanyfield', Serum.Form.Module.Fields.OneToMany);